
const express = require('express');
const router = express.Router();
const PatientModel = require('../db/PatientModel');
const DepartmentModel = require('../db/DepartmentModel');
const UserModel = require('../db/UserModel');
const ArrangeMesModel = require('../db/ArrangeMesModel');//排班信息
const RegistrationinformationModel = require('../db/RegistrationinforMation');//挂号表信息
const authhs256 = require("../middlewares/authhs256/authentication");//权限组件
const moment = require('moment');
const Fun = require('../middlewares/Fun');

//给医生排班信息数组重新排序  -升序
function compare(property) {
    return function (a, b) {
        var value1 = Date.parse(a[property]);
        var value2 = Date.parse(b[property]);
        return value1 - value2;
    }
}

//获取排班详情
router.get('/findarrange', (req, res) => {
    if (!req.query.starttime || !req.query.endtime) {
        return res.json({
            code: 202,
            mes: '参数错误。'
        });
    }
    let start = moment(req.query.starttime).format('YYYY/M/D');//每周周一的时间
    let end = moment(req.query.endtime).format('YYYY/M/D');
    let timearr;//分割时间数组
    let day;
    let tempA = [];//上午排班医生数组
    let tempB = [];//下午排班医生数组  { 'arrangemes.arrangetime': start }
    let obj;
    UserModel.find({ state: "启用" }, ['name']).then(user => {
        return ArrangeMesModel.find({ 'arrangemes.arrangetime': start }).lean(true).then(arrange => {

            return DepartmentModel.find({}, ['name']).then(department => {
                let userarr = {};
                try {
                    for (let i = 0; i < user.length; i++) {
                        userarr[user[i]._id] = user[i];
                    }
                    let departarr = {};
                    for (let i = 0; i < department.length; i++) {
                        departarr[department[i]._id] = department[i];
                    }
                    let pbarr = [];//每个医生的排班信息
                    for (let i = 0; i < arrange.length; i++) {//遍历所有医生
                        if (userarr[arrange[i].id]) {
                            if (arrange[i].role != "药房" && userarr[arrange[i].id]) {
                                arrange[i].department_name = departarr[arrange[i].department].name;
                                arrange[i].name = userarr[arrange[i].id].name;
                                start = moment(req.query.starttime).format('YYYY/M/D');
                                pbarr = arrange[i].arrangemes.sort(compare('arrangetime'));
                                for (let j = 0; j < pbarr.length; j++) {//遍历当前医生的所有排班信息，提取出本周的
                                    obj = {};
                                    timearr = start.split('/');
                                    day = new Date(timearr[0], timearr[1] - 1, timearr[2]);

                                    if (pbarr[j].arrangetime == start) {
                                        if (pbarr[j].arrangename == '早班' || pbarr[j].arrangename == '全班') {
                                            obj[start] = arrange[i].name + '-' + pbarr[j].arrangename + '-' + arrange[i].department_name;
                                            tempA.push(obj);
                                        }
                                        if (pbarr[j].arrangename == '晚班' || pbarr[j].arrangename == '全班') {
                                            obj[start] = arrange[i].name + '-' + pbarr[j].arrangename + '-' + arrange[i].department_name;
                                            tempB.push(obj);
                                        }
                                        if (start == end) {
                                            break;
                                        }
                                        start = moment(day.getTime()).add(1, 'days').format('YYYY/M/D');
                                    }
                                }
                            }
                        }
                    }
                } catch (error) {
                    console.log(error)
                }
                //Fun.saveLogs(req.user, req.ip, '首页展示排班信息操作');
                return res.json({
                    code: 200,
                    mes: '查询成功。',
                    forenoon: tempA,
                    afternoon: tempB
                });
            })
        })
    }).then(data => {

    })
        .catch(err => {
            Fun.saveLogs(req.user, req.ip, '首页展示排班信息操作');
            return res.json({
                code: 201,
                mes: '查询失败。'
            });
        })
});

//就诊情况列表
router.get('/findpatient', (req, res) => {
    if (!req.query.day) {
        return res.json({
            code: 202,
            mes: '参数错误。'
        });
    }

    let start = moment(new Date(req.query.day).getTime()).format('YYYY-MM-DD 00:00:00');
    let end = moment(new Date(req.query.day).getTime()).format('YYYY-MM-DD 23:59:59');
    let awaits = 0;//待接诊人数
    let complate = 0;//接诊中人数
    let done = 0;//已接诊人数
    PatientModel.count({ createtime: { $gte: start, $lte: end } }).then(patient => {
        return RegistrationinformationModel.find({ receptiontime: { $gte: start, $lte: end } }).sort({ receptiontime: 1 }).lean(true).then(docs => {//就诊总人数
            return RegistrationinformationModel.count({ receptiontime: { $gte: start, $lte: end } }).then(outpatient => {//门诊人数
                return Promise.all([PatientModel.find()]).then(temp => {
                    let user = temp[0];
                    let obj = {};
                    for (let i = 0; i < docs.length; i++) {
                        if (docs[i].receptionstate == 2) {//接诊状态  1  待分诊   2：待接诊   3：接诊中   4：已完成
                            awaits++;
                        } else if (docs[i].receptionstate == 3) {
                            complate++;
                        } else if (docs[i].receptionstate == 4) {
                            done++;
                        }
                    }
                    for (let i = 0; i < user.length; i++) {
                        obj[user[i]._id] = user[i];
                    }
                    for (let j = 0; j < docs.length; j++) {
                        docs[j].payer_name = obj[docs[j].payer].username;
                    }
                    return res.json({
                        code: 200,
                        mes: '查询成功。',
                        data: docs,
                        sum: patient,
                        outpatient: outpatient,
                        awaits: awaits,
                        complate: complate,
                        done: done
                    });
                })

            })
            //Fun.saveLogs(req.user, req.ip, '首页展示就诊信息操作');
        })
    }).catch(() => {
        Fun.saveLogs(req.user, req.ip, '首页展示就诊信息操作');
        return res.json({
            code: 201,
            mes: '查询失败。'
        });
    })
});

module.exports = router; 